package com.transaction.seataorder.aop;

import com.transaction.seataorder.exception.IdempotentException;
import com.transaction.seataorder.utils.TokenUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ausu
 * @version 1.0
 * @description: TODO
 * @date 2023/1/29 17:18
 */
@Aspect
@Component
public class IdempotentAspect {

    @Autowired
    private TokenUtil tokenUtil;

    @Pointcut("@annotation(com.transaction.seataorder.annoation.AutoIdempotent)")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint) throws IdempotentException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            tokenUtil.checkToken(request);
        } catch (IdempotentException e) {
            throw e;
        }

    }
}
